import 'package:carousel_slider/carousel_slider.dart';
import 'package:development_assistant/config/font.dart';
import 'package:development_assistant/config/image_config.dart';
import 'package:development_assistant/controller/database_controller.dart';
import 'package:development_assistant/model/db_info.dart';
import 'package:development_assistant/model/table_info.dart';
import 'package:development_assistant/ui/screen/widget/custom_text.dart';
import 'package:development_assistant/ui/screen/widget/home_background.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../config/colors.dart';
import '../../../model/column_info.dart';

class DatabaseAssistant extends StatelessWidget {

  final DatabaseController databaseController=Get.put(DatabaseController());
  DatabaseAssistant({super.key});

  @override
  Widget build(BuildContext context) {

    return FutureBuilder(
      future: databaseController.getDBList(),
      builder: (context,snapshot) {
        return HomeBackground(
            front: SingleChildScrollView(
              scrollDirection: Axis.vertical,
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 50.h,horizontal: 20.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _databaseType("MySQL"),
                    SizedBox(height: 10.h,),
                    _databaseInformation()
                  ],
                ),
              ),
            )
        );
      }
    );
  }

  _databaseType(String databaseType){
    return Row(
      children: [
        Image.asset(
          ImageConfig.databaseImage[databaseType]!,
          width: 70.w,
        ),
        SizedBox(width: 10.w,),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(databaseType,style: FontConfig.databaseNameStyle),
            Text("关系型数据库".tr)
          ],
        )
      ],
    );
  }

  _database(){
    return Obx(() => databaseController.dbInfoList.isEmpty?_databaseFigure():SizedBox(
      width: 350.w,
      height: 170.h,
      child: CarouselSlider(
        options: CarouselOptions(
            height: 350.0.h,
            aspectRatio: 16/9,
            initialPage: 0,
            enlargeCenterPage: true,
            onPageChanged: (index,reason){
              databaseController.pickIndex.value=index;
            }
        ),
        items: List<Widget>.generate(databaseController.dbInfoList.length, (index) {
          return Container(
              width: 320.w,
              margin: EdgeInsets.symmetric(vertical: 10.h),
              padding: EdgeInsets.symmetric(vertical: 15.h,horizontal: 20.w),
              decoration: BoxDecoration(
                  gradient:ColorsConfig().cardColorOfTheme,
                  borderRadius: BorderRadius.circular(20)
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      CustomText(text: "${databaseController.dbInfoList[index]["db_name"]}", textStyle: FontConfig.databaseNameStyle),
                      IconButton(
                          splashColor: Colors.transparent,
                          highlightColor: Colors.transparent,
                          onPressed: (){
                            databaseController.dbID.value=databaseController.dbInfoList[index]["db_id"];
                            databaseController.dbName.value=databaseController.dbInfoList[index]["db_name"];
                            databaseController.dbDesc.value=databaseController.dbInfoList[index]["db_desc"];
                            databaseController.dbHost.value=databaseController.dbInfoList[index]["db_host"];
                            databaseController.dbPort.value=databaseController.dbInfoList[index]["db_port"];
                            databaseController.dbUrl.value=databaseController.dbInfoList[index]["db_url"];
                            Get.toNamed("/EditDatabase");
                          },
                          icon: const Icon(Icons.more_horiz)
                      )
                    ],
                  ),
                  CustomText(text: "${'描述'.tr} : ${databaseController.dbInfoList[index]["db_desc"]}", textStyle:FontConfig.databaseInformationStyle),
                  CustomText(text: "${'主机号'.tr} : ${databaseController.dbInfoList[index]["db_host"]}", textStyle:FontConfig.databaseInformationStyle),
                  CustomText(text: "${'端口号'.tr} : ${databaseController.dbInfoList[index]["db_port"]}", textStyle:FontConfig.databaseInformationStyle),
                  CustomText(text: "Url : ${databaseController.dbInfoList[index]["db_url"]}", textStyle:FontConfig.databaseInformationStyle)
                ],
              )
          );
        }),
      ),
    ));
  }

  _table(){
    return Obx(() =>databaseController.tableInfoList.isEmpty?_tableFigure(): Wrap(
      children: List<Widget>.generate(databaseController.tableInfoList[databaseController.pickIndex.value].length, (index) {
        return Container(
            width: 300.w,
            height: 90.h,
            margin: EdgeInsets.symmetric(vertical: 7.h),
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            decoration: BoxDecoration(
                gradient: ColorsConfig().cardColorOfTheme,
                borderRadius: BorderRadius.circular(20)
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    CustomText(text: "${databaseController.tableInfoList[databaseController.pickIndex.value][index]['table_name']}", textStyle: FontConfig.databaseNameStyle),

                    IconButton(
                        splashColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                        onPressed: (){
                          TableInfo tableInfo=TableInfo.fromJson(databaseController.tableInfoList[databaseController.pickIndex.value][index]);
                          databaseController.tableID.value=tableInfo.tableID!;
                          databaseController.tableName.value=tableInfo.tableName;
                          databaseController.tableSort.value=tableInfo.tableSort;
                          databaseController.tableEngine.value=tableInfo.tableEngine;
                          databaseController.tableDBID.value=tableInfo.dbID;
                          databaseController.columns=databaseController.columnInfoList[databaseController.pickIndex.value][index];

                          Get.toNamed("/TableDetail");
                        },
                        icon: const Icon(Icons.more_horiz)
                    ),
                  ],
                ),
                CustomText(text: "${databaseController.tableInfoList[databaseController.pickIndex.value][index]['table_engine']}", textStyle: FontConfig.databaseInformationStyle),
                CustomText(text: "${databaseController.tableInfoList[databaseController.pickIndex.value][index]['table_sort']}", textStyle: FontConfig.databaseInformationStyle),
              ],
            )
        );
      }),
    ));
  }

  _databaseInformation(){
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text("数据库".tr,style: FontConfig.titleStyle,),
            ElevatedButton.icon(
              onPressed: (){
                databaseController.columnList.removeRange(1,databaseController.columnList.length);
                databaseController.tableList.removeRange(1,databaseController.tableList.length);
                Get.toNamed("/AddDatabase");
              },
              icon: const Icon(Icons.create),
              label: Text("新建".tr),
              style: ElevatedButton.styleFrom(
                  backgroundColor: ColorsConfig().buttonColorOfTheme,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10)
                  )
              ),
            ),
          ],
        ),
        _database(),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text("数据表".tr,style: FontConfig.titleStyle,),
            ElevatedButton.icon(
              onPressed: (){
                if(databaseController.dbInfoList.isNotEmpty){
                  ColumnInfo column=ColumnInfo(null,0,"", "", "");
                  databaseController.tableDBID.value=databaseController.dbInfoList[databaseController.pickIndex.value]["db_id"];
                  databaseController.tableName.value="";
                  databaseController.tableEngine.value="";
                  databaseController.tableSort.value="";
                  databaseController.columns.add(column);
                  Get.toNamed("/AddTable");
                }else{
                  Get.snackbar("添加数据表失败".tr,"请先添加数据库".tr);
                }
              },
              icon: const Icon(Icons.add),
              label: Text("添加".tr),
              style: ElevatedButton.styleFrom(
                  backgroundColor:  ColorsConfig().buttonColorOfTheme,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10)
                  )
              ),
            ),
          ],
        ),
        _table()
      ],
    );
  }

  _databaseFigure(){
    return Container(
      height: 160.h,
      margin: EdgeInsets.symmetric(vertical: 10.h),
      padding: EdgeInsets.symmetric(horizontal: 5.w),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(15),
          gradient: ColorsConfig().figureOfTheme
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            ImageConfig.figureImage['db']!,
            width: 160.w,
          ),
          Container(
            width: 150.w,
            padding: EdgeInsets.symmetric(vertical: 40.h),
            child: Column(
              children: [
                Text("数据库管理".tr,style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 15.sp),),
                SizedBox(height: 5.h,),
                Text("记录开发过程中的数据库".tr,style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 10.sp),),
              ],
            ),
          )
        ],
      ),
    );
  }

  _tableFigure(){
    return Container(
      height: 230.h,
      width: 320.w,
      margin: EdgeInsets.symmetric(vertical: 10.h),
      padding: EdgeInsets.symmetric(vertical: 5.h),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(15),
          gradient: ColorsConfig().figureOfTheme
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text("数据库表信息".tr,style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 15.sp),),
          SizedBox(height: 5.h,),
          Text("每时每刻可以了解到数据库信息".tr,style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 10.sp),),
          Text("能够快速搭建所需要的数据库".tr,style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 10.sp),),
          Image.asset(
            ImageConfig.figureImage['table']!,
            width:150.w,
          ),
        ],
      ),
    );
  }


}
